package com.p7.notepad.network.support;


import android.util.Log;

import com.p7.notepad.network.exception.ERROR;
import com.p7.notepad.network.exception.ExceptionHandle;
import com.p7.notepad.network.listener.RequestListener;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * Created by 12262 on 2016/5/30.
 */
public class RequestObserver implements Observer<ResponseBody> {

    private RequestListener listener;
    public RequestObserver(RequestListener listener) {
        this.listener = listener;
    }

    private Disposable mDisposable;
    @Override
    public void onSubscribe(Disposable d) {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        mDisposable = d;
    }

    @Override
    public void onNext(ResponseBody body) {
        if (listener != null) {
            try {
                String s = body.string();
                Log.d("请求结果", s);
                listener.onSuccess(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mDisposable.dispose();
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof ExceptionHandle.ResponeThrowable) {
            if (listener != null) {
                listener.onError((ExceptionHandle.ResponeThrowable) e);
            }
        } else {
            if (listener != null) {
                listener.onError(new ExceptionHandle.ResponeThrowable(e, ERROR.UNKNOWN));
            }
        }
        mDisposable.dispose();
    }

    @Override
    public void onComplete() {

    }
}

